﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Objects;
using System.Globalization;
using System.Linq;
using EstateNuke.Data.Properties;

namespace EstateNuke.Data
{
    public partial class Building
    {
        #region Fileds & Properties

        /// <summary>
        /// </summary>
        public string DisplayName
        {
            get
            {
                if (!ProjectReference.IsLoaded)
                {
                    ProjectReference.Load(MergeOption.PreserveChanges);
                }
                return string.Format("{0}-{1}{2}", Project.DisplayName, Name, IsDeleted ? " (已删除)" : "");
            }
        }

        /// <summary>
        /// </summary>
        public IList<Entrance> Entrances
        {
            get
            {
                return InternalEntrances.Where(entrance => entrance.IsDeleted == false).ToList();
            }
        }

        /// <summary>
        /// </summary>
        public IList<Entrance> AllEntrances
        {
            get
            {
                return InternalEntrances.ToList();
            }
        }

        /// <summary>
        /// </summary>
        public IList<Floor> Floors
        {
            get
            {
                return InternalFloors.Where(floor => floor.IsDeleted == false).ToList();
            }
        }

        /// <summary>
        /// </summary>
        public IList<Floor> AllFloors
        {
            get
            {
                return InternalFloors.ToList();
            }
        }

        /// <summary>
        /// </summary>
        public IList<Room> Rooms
        {
            get
            {
                return InternalEntrances.Where(entrance => entrance.IsDeleted == false).SelectMany(entrance => entrance.InternalRooms).Where(room => room.IsDeleted == false).ToList();
            }
        }

        /// <summary>
        /// </summary>
        public IList<Room> AllRooms
        {
            get
            {
                return InternalEntrances.SelectMany(entrance => entrance.InternalRooms).ToList();
            }
        }

        /// <summary>
        /// </summary>
        public IList<Property> Properties
        {
            get
            {
                return InternalFloors.Where(floor => floor.IsDeleted == false).SelectMany(floor => floor.InternalProperties).Where(property => property.IsDeleted == false).ToList();
            }
        }

        /// <summary>
        /// </summary>
        public IList<Property> AllProperties
        {
            get
            {
                return InternalFloors.SelectMany(floor => floor.InternalProperties).ToList();
            }
        }

        #endregion

        #region Set BuildingState

        /// <summary>
        /// </summary>
        public void SetBuildingStateReady(User modifiedUser)
        {
            if (modifiedUser == null)
            {
                throw new ArgumentNullException("modifiedUser");
            }
            BuildingStateId = 1;
            ModifiedDate = DateTime.Now;
            ModifiedByUser = modifiedUser;
        }

        /// <summary>
        /// </summary>
        public void SetBuildingStateFrozen(User modifiedUser)
        {
            if (modifiedUser == null)
            {
                throw new ArgumentNullException("modifiedUser");
            }
            BuildingStateId = 2;
            ModifiedDate = DateTime.Now;
            ModifiedByUser = modifiedUser;
        }

        #endregion

        #region Add & Remove Entrance

        /// <summary>
        /// </summary>
        /// <returns></returns>
        public Entrance AddEntrance(User modifiedUser)
        {
            if (modifiedUser == null)
            {
                throw new ArgumentNullException("modifiedUser");
            }
            var entrance = new Entrance
                               {
                                   RowId = Guid.NewGuid(),
                                   CreatedDate = DateTime.Now,
                               };
            InternalEntrances.Add(entrance);
            entrance.IsDeleted = false;
            entrance.ModifiedDate = DateTime.Now;
            entrance.ModifiedByUser = modifiedUser;
            entrance.RoomsNumberPerFloor = 1;
            entrance.PropertiesNumberPerFloor = 1;
            return entrance;
        }

        /// <summary>
        /// </summary>
        /// <param name = "name"></param>
        /// <param name = "modifiedUser"></param>
        /// <returns></returns>
        public Entrance AddEntrance(string name, User modifiedUser)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException("name");
            }
            if (modifiedUser == null)
            {
                throw new ArgumentNullException("modifiedUser");
            }
            if (InternalEntrances.Any(item => item.IsDeleted == false && item.Name == name))
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.DuplicatedEntrance, name));
            }
            var entrance = InternalEntrances.FirstOrDefault(item => item.IsDeleted && item.Name == name);
            if (entrance == null)
            {
                entrance = new Entrance
                               {
                                   RowId = Guid.NewGuid(),
                                   CreatedDate = DateTime.Now,
                               };
                InternalEntrances.Add(entrance);
            }
            entrance.IsDeleted = false;
            entrance.ModifiedDate = DateTime.Now;
            entrance.ModifiedByUser = modifiedUser;
            entrance.Name = name;
            entrance.RoomsNumberPerFloor = 1;
            entrance.PropertiesNumberPerFloor = 1;
            return entrance;
        }

        /// <summary>
        /// </summary>
        /// <param name = "number"></param>
        /// <param name = "modifiedUser"></param>
        /// <returns></returns>
        public Entrance AddEntrance(short number, User modifiedUser)
        {
            if (modifiedUser == null)
            {
                throw new ArgumentNullException("modifiedUser");
            }
            if (InternalEntrances.Any(item => item.IsDeleted == false && item.Number == number))
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.DuplicatedEntrance, number));
            }
            var entrance = InternalEntrances.FirstOrDefault(item => item.IsDeleted && item.Number == number);
            if (entrance == null)
            {
                entrance = new Entrance
                               {
                                   RowId = Guid.NewGuid(),
                                   CreatedDate = DateTime.Now,
                               };
                InternalEntrances.Add(entrance);
            }
            entrance.IsDeleted = false;
            entrance.ModifiedDate = DateTime.Now;
            entrance.ModifiedByUser = modifiedUser;
            entrance.Number = number;
            entrance.RoomsNumberPerFloor = 1;
            entrance.PropertiesNumberPerFloor = 1;
            return entrance;
        }

        /// <summary>
        /// </summary>
        /// <param name = "name"></param>
        /// <param name = "number"></param>
        /// <param name = "modifiedUser"></param>
        /// <returns></returns>
        public Entrance AddEntrance(string name, short number, User modifiedUser)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException("name");
            }
            if (modifiedUser == null)
            {
                throw new ArgumentNullException("modifiedUser");
            }
            if (InternalEntrances.Any(item => item.IsDeleted == false && (item.Name == name || item.Number == number)))
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.DuplicatedEntrance, string.Format("{0}({1})", name, number)));
            }
            var entrance = InternalEntrances.FirstOrDefault(item => item.IsDeleted && (item.Name == name || item.Number == number));
            if (entrance == null)
            {
                entrance = new Entrance
                               {
                                   RowId = Guid.NewGuid(),
                                   CreatedDate = DateTime.Now,
                               };
                InternalEntrances.Add(entrance);
            }
            entrance.IsDeleted = false;
            entrance.ModifiedDate = DateTime.Now;
            entrance.ModifiedByUser = modifiedUser;
            entrance.Name = name;
            entrance.Number = number;
            entrance.RoomsNumberPerFloor = 1;
            entrance.PropertiesNumberPerFloor = 1;
            return entrance;
        }

        /// <summary>
        /// </summary>
        /// <param name = "entrance"></param>
        /// <param name = "modifiedUser"></param>
        public void RemoveEntrance(Entrance entrance, User modifiedUser)
        {
            if (entrance == null)
            {
                throw new ArgumentNullException("entrance");
            }
            if (modifiedUser == null)
            {
                throw new ArgumentNullException("modifiedUser");
            }
            if (InternalEntrances.Contains(entrance))
            {
                entrance.Delete(modifiedUser);
            }
        }

        #endregion

        #region Generate Entrances

        /// <summary>
        /// </summary>
        /// <param name = "modifiedUser"></param>
        public void GenerateEntrances(User modifiedUser)
        {
            GenerateEntrances(EntrancesNumber, modifiedUser);
        }

        /// <summary>
        /// </summary>
        /// <param name = "entrancesNumber"></param>
        /// <param name = "modifiedUser"></param>
        public void GenerateEntrances(short entrancesNumber, User modifiedUser)
        {
            if (modifiedUser == null)
            {
                throw new ArgumentNullException("modifiedUser");
            }
            if (entrancesNumber < 0)
            {
                throw new ArgumentOutOfRangeException("entrancesNumber");
            }
            var entrances = InternalEntrances.Where(entrance => entrance.Number >= 0).ToList();
            for (short entranceNumber = 1; entranceNumber <= entrancesNumber; entranceNumber++)
            {
                var currentEntrance = entrances.FirstOrDefault(entrance => entrance.Number == entranceNumber);
                if (currentEntrance == null)
                {
                    AddEntrance(string.Format("{0}号", entranceNumber), entranceNumber, modifiedUser);
                }
            }
        }

        #endregion

        #region Add & Remove Floor

        /// <summary>
        /// </summary>
        /// <returns></returns>
        public Floor AddFloor(User modifiedUser)
        {
            if (modifiedUser == null)
            {
                throw new ArgumentNullException("modifiedUser");
            }
            var floor = new Floor
                            {
                                RowId = Guid.NewGuid(),
                                CreatedDate = DateTime.Now,
                            };
            InternalFloors.Add(floor);
            floor.IsDeleted = false;
            floor.ModifiedDate = DateTime.Now;
            floor.ModifiedByUser = modifiedUser;
            return floor;
        }

        /// <summary>
        /// </summary>
        /// <param name = "name"></param>
        /// <param name = "modifiedUser"></param>
        /// <returns></returns>
        public Floor AddFloor(string name, User modifiedUser)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException("name");
            }
            if (modifiedUser == null)
            {
                throw new ArgumentNullException("modifiedUser");
            }
            if (InternalFloors.Any(item => item.IsDeleted == false && item.Name == name))
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.DuplicatedFloor, name));
            }
            var floor = InternalFloors.FirstOrDefault(item => item.IsDeleted && item.Name == name);
            if (floor == null)
            {
                floor = new Floor
                            {
                                RowId = Guid.NewGuid(),
                                CreatedDate = DateTime.Now,
                            };
                InternalFloors.Add(floor);
            }
            floor.IsDeleted = false;
            floor.ModifiedDate = DateTime.Now;
            floor.ModifiedByUser = modifiedUser;
            floor.Name = name;
            return floor;
        }

        /// <summary>
        /// </summary>
        /// <param name = "number"></param>
        /// <param name = "modifiedUser"></param>
        /// <returns></returns>
        public Floor AddFloor(short number, User modifiedUser)
        {
            if (modifiedUser == null)
            {
                throw new ArgumentNullException("modifiedUser");
            }
            if (InternalFloors.Any(item => item.IsDeleted == false && item.Number == number))
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.DuplicatedFloor, number));
            }
            var floor = InternalFloors.FirstOrDefault(item => item.IsDeleted && item.Number == number);
            if (floor == null)
            {
                floor = new Floor
                            {
                                RowId = Guid.NewGuid(),
                                CreatedDate = DateTime.Now,
                            };
                InternalFloors.Add(floor);
            }
            floor.IsDeleted = false;
            floor.ModifiedDate = DateTime.Now;
            floor.ModifiedByUser = modifiedUser;
            floor.Number = number;
            return floor;
        }

        /// <summary>
        /// </summary>
        /// <param name = "name"></param>
        /// <param name = "number"></param>
        /// <param name = "modifiedUser"></param>
        /// <returns></returns>
        public Floor AddFloor(string name, short number, User modifiedUser)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException("name");
            }
            if (modifiedUser == null)
            {
                throw new ArgumentNullException("modifiedUser");
            }
            if (InternalFloors.Any(item => item.IsDeleted == false && (item.Name == name || item.Number == number)))
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.DuplicatedFloor, string.Format("{0}({1})", name, number)));
            }
            var floor = InternalFloors.FirstOrDefault(item => item.IsDeleted && (item.Name == name || item.Number == number));
            if (floor == null)
            {
                floor = new Floor
                            {
                                RowId = Guid.NewGuid(),
                                CreatedDate = DateTime.Now,
                            };
                InternalFloors.Add(floor);
            }
            floor.IsDeleted = false;
            floor.ModifiedDate = DateTime.Now;
            floor.ModifiedByUser = modifiedUser;
            floor.Name = name;
            floor.Number = number;
            return floor;
        }

        /// <summary>
        /// </summary>
        /// <param name = "floor"></param>
        /// <param name = "modifiedUser"></param>
        public void RemoveFloor(Floor floor, User modifiedUser)
        {
            if (floor == null)
            {
                throw new ArgumentNullException("floor");
            }
            if (modifiedUser == null)
            {
                throw new ArgumentNullException("modifiedUser");
            }
            if (InternalFloors.Contains(floor))
            {
                floor.Delete(modifiedUser);
            }
        }

        #endregion

        #region Generate Floors

        /// <summary>
        /// </summary>
        /// <param name = "modifiedUser"></param>
        public void GenerateFloors(User modifiedUser)
        {
            GenerateFloors(FloorsNumber, UndergroundFloorsNumber, modifiedUser);
        }

        /// <summary>
        /// </summary>
        /// <param name = "floorsNumber"></param>
        /// <param name = "undergroundFloorsNumber"></param>
        /// <param name = "modifiedUser"></param>
        public void GenerateFloors(short floorsNumber, short undergroundFloorsNumber, User modifiedUser)
        {
            if (modifiedUser == null)
            {
                throw new ArgumentNullException("modifiedUser");
            }
            if (floorsNumber < 0)
            {
                throw new ArgumentOutOfRangeException("floorsNumber");
            }
            if (undergroundFloorsNumber < 0)
            {
                throw new ArgumentOutOfRangeException("undergroundFloorsNumber");
            }
            var floors = InternalFloors.Where(floor => floor.Number >= 0).ToList();
            for (short floorNumber = 1; floorNumber <= floorsNumber; floorNumber++)
            {
                var currentFloor = floors.FirstOrDefault(floor => floor.Number == floorNumber);
                if (currentFloor == null)
                {
                    AddFloor(string.Format("{0}层", floorNumber), floorNumber, modifiedUser);
                }
            }
            var undergroundFloors = InternalFloors.Where(floor => floor.Number < 0).ToList();
            for (short floorNumber = 1; floorNumber <= undergroundFloorsNumber; floorNumber++)
            {
                var currentFloor = undergroundFloors.FirstOrDefault(floor => floor.Number == -floorNumber);
                if (currentFloor == null)
                {
                    AddFloor(string.Format("地下{0}层", floorNumber), floorNumber, modifiedUser);
                }
            }
        }

        #endregion

        #region Generate Rooms

        /// <summary>
        /// </summary>
        /// <param name = "modifiedUser"></param>
        public void GenerateRooms(User modifiedUser)
        {
            if (modifiedUser == null)
            {
                throw new ArgumentNullException("modifiedUser");
            }
            foreach (var entrance in AllEntrances)
            {
                entrance.GenerateRooms(modifiedUser);
            }
        }

        #endregion

        #region Generate Properties

        /// <summary>
        /// </summary>
        /// <param name = "modifiedUser"></param>
        public void GenerateProperties(User modifiedUser)
        {
            if (modifiedUser == null)
            {
                throw new ArgumentNullException("modifiedUser");
            }
            foreach (var entrance in AllEntrances)
            {
                entrance.GenerateProperties(modifiedUser);
            }
        }

        #endregion

        #region Ensure

        /// <summary>
        /// </summary>
        public void Ensure()
        {
            if (string.IsNullOrEmpty(Name))
            {
                throw new EntityException(string.Format(CultureInfo.CurrentCulture, Resources.NotNullAllowed, RowId, "Building", "Name"));
            }
            if (EntrancesNumber < 0)
            {
                throw new EntityException(string.Format(CultureInfo.CurrentCulture, Resources.NonNegativeNumberAllowed, RowId, "Building", "EntrancesNumber"));
            }
            if (FloorsNumber < 0)
            {
                throw new EntityException(string.Format(CultureInfo.CurrentCulture, Resources.NonNegativeNumberAllowed, RowId, "Building", "FloorsNumber"));
            }
            if (UndergroundFloorsNumber < 0)
            {
                throw new EntityException(string.Format(CultureInfo.CurrentCulture, Resources.NonNegativeNumberAllowed, RowId, "Building", "UndergroundFloorsNumber"));
            }
            Name = Name.Length > 64 ? Name.Substring(0, 64) : Name;
        }

        #endregion

        #region Delete

        /// <summary>
        /// </summary>
        public void Delete(User modifiedUser)
        {
            if (modifiedUser == null)
            {
                throw new ArgumentNullException("modifiedUser");
            }
            IsDeleted = true;
            ModifiedDate = DateTime.Now;
            ModifiedByUser = modifiedUser;
            ((List<Entrance>) Entrances).ForEach(entrance => entrance.Delete(modifiedUser));
            ((List<Floor>) Floors).ForEach(floor => floor.Delete(modifiedUser));
        }

        /// <summary>
        /// </summary>
        public void CancelDelete(User modifiedUser)
        {
            if (modifiedUser == null)
            {
                throw new ArgumentNullException("modifiedUser");
            }
            IsDeleted = false;
            ModifiedDate = DateTime.Now;
            ModifiedByUser = modifiedUser;
        }

        #endregion
    }
}